package com.basker.pisces.core.meta.bean;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.basker.pisces.core.meta.IDataObjectMeta;
import com.basker.pisces.core.meta.ObjectMetaNameHelper;
import com.basker.pisces.core.meta.utils.DataObjectMetaUtils;

public class PartBeanMeta extends BeanMeta {

    protected String[] loadFields;
    protected Set<String> loadFieldSet;

    PartBeanMeta(Class<?> beanClass, String[] loadFields) {
        super(beanClass);
        this.setLoadFields(loadFields);
    }

    @Override
    protected IDataObjectMeta createCollectionMeta(String fieldName, Class<?> itemClass) {
        List<String> itemMetaLoadFields = DataObjectMetaUtils.filterByPrefix(fieldName, Arrays.asList(loadFields),
                true);

        return BeanMetaManager.getPartBeanMeta(itemClass,
                itemMetaLoadFields.toArray(new String[itemMetaLoadFields.size()]));
    }

    @Override
    protected boolean validField(String name) {
        return loadFieldSet != null ? loadFieldSet.contains(name) : true;
    }

    private void setLoadFields(String[] loadFields) {
        this.setName(ObjectMetaNameHelper.generatePartMetaName(this.getName(), loadFields));
        this.loadFields = loadFields;
        // 对于当前契约的成员，将A.1,A.2,B.1,B.2的成员，转换成A,B
        this.loadFieldSet = Stream.of(loadFields).map(m -> m.split("\\.")[0]).collect(Collectors.toSet());
    }
}
